﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Claims;
using AutoMapper;
using DefenseQuestion.Repositorys;
using Microsoft.Extensions.Configuration;
using DefenseQuestion.Application.UserApplication.Dto;
using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using DefenseQuestion.Utility;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Exceptions;


namespace DefenseQuestion.Application.UserApplication
{
    public class UserService : IUserService
    {
        private readonly IBaseRepository<User> User;
        private readonly IBaseRepository<UserType> userType;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;


        public UserService(IBaseRepository<User> user, IBaseRepository<UserType> userType, IMapper mapper, IConfiguration configuration)
        {
            User = user;
            this.userType = userType;
            this.mapper = mapper;
            this.configuration = configuration;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<LoginResultDto> LoginAsync(LoginDto dto)
        {
            var user = await User.FindAsync(m => m.Account == dto.Account && m.IsDel == false);
            if (user == null)
            {
                return new LoginResultDto { Code = Result.Success, Info = LoginInfo.NoneUser, Message = "无此用户" };
            }
            else
            {
                if (user.Password.ToUpper() == dto.Password.Md5().ToUpper())
                {
                    //更新末次登录IP和末次登录时间
                    //user.LastIP = httpContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                    //user.LastTime = DateTime.Now;
                    //User.Update(user);

                    //身份信息认证
                    //写Session或Cookies换成JWT
                    IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,user.UserId.ToString()),
                        new Claim(JwtClaimTypes.Name,user.Account),
                        //new Claim(ClaimTypes.Name,user.UserAccount),
                    };

                    //JWT密钥
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"]));

                    //算法
                    var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    //过期时间
                    DateTime expires = DateTime.UtcNow.AddHours(10);

                    //Payload负载
                    var token = new JwtSecurityToken(
                        issuer: configuration["JwtConfig:Issuer"],
                        audience: configuration["JwtConfig:Audience"],
                        claims: claims,
                        notBefore: DateTime.UtcNow,
                        expires: expires,
                        signingCredentials: cred
                        );

                    var handler = new JwtSecurityTokenHandler();

                    //生成令牌
                    string jwt = handler.WriteToken(token);

                    return new LoginResultDto { Code = Result.Success, Info = LoginInfo.Success, Message = "登录成功", Token = jwt };
                }
                else
                {
                    return new LoginResultDto { Code = Result.Failure, Info = LoginInfo.PasswordError, Message = "密码不正确" };
                }
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResultDto<User>> AddUserAsync(AddUserDto user)
        {
            var Uname = User.Queryable().Where(x => x.Account == user.Account).ToList();
            if (Uname.Count != 0)
            {
                return new ResultDto<User> { Code = Result.Success, Message = "已有此用户" };
            }
            user.Password = user.Password.Md5().ToUpper();
            var list = mapper.Map<AddUserDto, User>(user);
            list.CreateName = user.Account;
            list.CreateDate = DateTime.Now;
            await User.AddAsync(list);
            return new ResultDto<User> { Code = Result.Success, Message = "注册成功" };
        }

        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResultDto<User>> UpdateUserAsync(AddUserDto user)
        {
            var OidUser = await User.FindAsync(user.UserId);

            mapper.Map(OidUser, user);
            if (User.Queryable().Where(x => x.Account == user.Account).ToList().Count != 0)
            {
                return new ResultDto<User> { Code = Result.Success, Message = "用户名已存在" };
            }
            else
            {
                var dto = mapper.Map(user, OidUser);
                await User.UpdateAsync(dto);
                return new ResultDto<User> { Code = Result.Success, Message = "注册成功" };
            }
        }

        /// <summary>
        /// 通过Id查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ResultDto<User> FindUser(int id)
        {
            var data = User.Queryable().FirstOrDefault(x => x.UserId == id);
            return new ResultDto<User> { Code = Result.Success, Data = data };
        }

        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> DeleteUserAsync(int id)
        {
            var isOk = false;
            var list = User.Queryable().Where(x => x.UserId == id);
            foreach (var item in list.ToList())
            {
                item.DeleteName = "删除人:" + item.Account;
                item.IsDel = true;
                item.DeleteDate = DateTime.Now;
                await User.UpdateAsync(item);
                isOk = true;
            }
            return new ResultDto<bool> { Code = Result.Success };
        }

        /// <summary>
        /// 用户分页查询显示
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public QusetionListResultDto<List<User>> GetUsersAsync(string userName, int pageIndex, int pageSize)
        {
            var list = User.Queryable().Where(x => x.IsDel == false).ToList();
            if (!string.IsNullOrEmpty(userName))
            {
                list = list.Where(x => x.Account.Contains(userName)).ToList();
            }
            var totalCount = list.Count();
            list = list.OrderBy(x => x.UserId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new QusetionListResultDto<List<User>> { Code = Result.Success, totalCount = totalCount, Data = list };
        }

        /// <summary>
        /// 获取用户类型
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<UserType>> GetUserType()
        {
            try
            {
                var list = userType.Queryable();
                return new ResultDto<List<UserType>>
                {
                    Data = list.ToList(),
                    Code = Result.Success,
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 手机短信验证
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="code"></param>
        public void SendVerificationCode(string phoneNumber, string code)
        {
            
        }
    }
}
